<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !assetDetailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :filter-btn="filterInfo.btn"
        >
          <template v-slot:filter-businessDate>
            <el-date-picker
              v-model="businessDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-del>
            <el-button :disabled="!canDelete" @click="del()">删除</el-button>
          </template>
          <template v-slot:filter-summary>
            <el-button :disabled="!canSummary" @click="summary()"
              >汇总</el-button
            >
          </template>
          <template v-slot:filter-cancelSummary>
            <el-button :disabled="!canCancelSummary" @click="cancelSummary()"
              >取消汇总</el-button
            >
          </template>
          <template v-slot:filter-uploadExcel>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入</el-button>
            </el-upload>
          </template>
        </NewPageFilter>
      </div>

      <!-- 表格 -->
      <TableContainer
        ref="table"
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-assetCode="scope">
          <span
            v-if="scope.row.assetCode"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.assetCode }}</span
          >
          <span v-else>-</span>
        </template>
      </TableContainer>
    </div>
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <assetCard-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      @returnBack="getList"
    />
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
          <el-radio label="select">仅选择数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="incomeCost">
import {
  exportIncomeCostDetail,
  cancelSummaryIncomeCostDetail,
  pullDataIncomeCostDetail,
  syncDataIncomeCostDetail,
  summaryIncomeCostDetail,
  getIncomeCostDetailPage,
  deleteIncomeCostDetail,
  summaryAllIncomeCostDetail,
} from '@/api/asset'
import Modify from './modify'
import { exportTemplateExcel } from '@/api/pub.js'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'
import { getSupplierAll, getDeptAll, getDepotAll } from '@/api/core'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useRoute } from 'vue-router'
const $route = useRoute()
const { proxy } = getCurrentInstance()
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: 'page',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '导出',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/asset/incomeCostDetail/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 过滤相关配置
const businessDate = ref([])
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    // deptAuth: 'id',
    // supplierAuth: 'supplierId',
    // depotAuth: 'id',
  },
  list: [
    {
      label: '业务日期',
      value: 'businessDate',
      slot: 'true',
      event: search,
    },
    {
      componentType: 'input',
      label: '资产卡片号',
      value: 'assetCodeLike',
      event: search,
    },
    {
      componentType: 'input',
      label: '资产名称',
      value: 'assetNameLike',
      event: search,
    },
    {
      componentType: 'input',
      label: '厂家名称',
      value: 'brandNameLike',
      event: search,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: {
        // supplierAuth: 'supplierId',
        sort: 'create_time desc',
      },
      clearable: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      multiple: true,
      event: search,
    },
    {
      label: '仓库',
      value: 'depotIdMult',
      query: {
        // depotAuth: 'id',
        status: 1,
      },
      api: getDepotAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '使用部门',
      value: 'useDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '管理部门',
      value: 'manageDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      componentType: 'select-model',
      label: '数据来源',
      value: 'sourceTypeMult',
      code: 'asset_income_cost_source',
      multiple: true,
      event: search,
    },
    {
      label: '申请部门',
      value: 'applyDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '执行部门',
      value: 'executeDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      componentType: 'input',
      label: '开单医生',
      value: 'applyDoctorLike',
      event: search,
    },
    {
      componentType: 'input',
      label: '执行医生',
      value: 'executeDoctorLike',
      event: search,
    },
  ],
  btn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('incomeCost:add'),
    },
    {
      type: 'slot',
      value: 'del',
      show: proxy.$permission('incomeCost:del'),
    },
    {
      type: 'slot',
      label: '汇总',
      value: 'summary',
      show: proxy.$permission('incomeCost:summary'),
    },
    {
      type: 'slot',
      label: '取消汇总',
      value: 'cancelSummary',
      show: proxy.$permission('incomeCost:cancelSummary'),
    },
    {
      type: 'button',
      label: '全部汇总',
      event: allSummary,
      show: proxy.$permission('incomeCost:allSummary'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('incomeCost:downloadTemplate'),
    },
    {
      type: 'slot',
      label: '导入',
      value: 'uploadExcel',
      show: proxy.$permission('incomeCost:import'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('incomeCost:exportExcel'),
    },
    {
      type: 'button',
      label: '拉取最新数据',
      event: pullData,
      show: proxy.$permission('incomeCost:pullData'),
    },
    {
      type: 'button',
      label: '手动同步数据',
      event: syncData,
      show: proxy.$permission('incomeCost:pullData'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
  fieldList1: [
    {
      label: '业务日期',
      value: 'businessDate',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'slot',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '供应商', value: 'supplierName' },
    { label: '仓库', value: 'depotName' },
    { label: '使用部门', value: 'useDeptName' },
    { label: '管理部门', value: 'manageDeptName' },
    { label: '位置', value: 'location' },
    {
      label: '申请部门',
      value: 'applyDeptName',
    },
    {
      label: '开单医生',
      value: 'applyDoctor',
    },
    {
      label: '执行部门',
      value: 'executeDeptName',
    },
    {
      label: '执行医生',
      value: 'executeDoctor',
    },
    { label: '数据来源', value: 'sourceTypeValue' },
    {
      label: '检查(治疗)人次',
      value: 'treatPersonTime',
    },
    {
      label: '阳性人次',
      value: 'positivePersonTime',
    },
    {
      label: '收入金额(元)',
      value: 'incomeAmount',
    },
    {
      label: '开机时长(h)',
      value: 'powerUpTime',
    },
  ],
  fieldList2: [
    {
      label: '是否汇总',
      value: 'statusValue',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('incomeCost:update'),
        ifRender: function (row) {
          return row.sourceType === 1 && row.status === 2
        },
      },
      {
        label: '删除',
        event: del,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('incomeCost:del'),
        ifRender: function (row) {
          return row.sourceType === 1 && row.status === 2
        },
      },
      {
        label: '汇总',
        event: summary,
        show: proxy.$permission('incomeCost:summary'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '取消汇总',
        event: cancelSummary,
        show: proxy.$permission('incomeCost:cancelSummary'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
})
const page = ref({
  // isPagerByExport: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'incomeCost' && el.url === val.url) {
                modifyInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  let data = {
                    id: val.businessId,
                  }
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

watch(
  () => proxy.$router,
  (route) => {
    if (
      route.currentRoute.value.name === 'incomeCost' &&
      route.currentRoute.value.params.query
    ) {
      let query = JSON.parse(route.currentRoute.value.params.query)
      filterInfo.value.query.assetId = query.assetId
      filterInfo.value.query.applyDeptIdMult = String(query.applyDeptId)
      filterInfo.value.query.businessDateGreater = query.businessDateGreater
      filterInfo.value.query.businessDateLess = query.businessDateLess
      filterInfo.value.query.assetCodeLike = query.assetCode
      businessDate.value = [query.businessDateGreater, query.businessDateLess]
      getCostFieldList()
    }
  },
  {
    deep: true,
    immediate: true,
  }
)

const canSummary = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((row) => row.status !== 2).length === 0
  )
})
const canDelete = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter(
      (row) => !(row.sourceType === 1 && row.status === 2)
    ).length === 0
  )
})
const canCancelSummary = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((row) => row.status !== 1).length === 0
  )
})
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  exportExcelList()
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = 'page'
}
function exportExcelList() {
  filterInfo.value.query.idMult = ''
  if (dialogInfo.value.flag === 'select') {
    if (!tableInfo.value.selections.length) {
      ElMessage.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
    let ids = tableInfo.value.selections.map((item) => item.id).join(',')
    filterInfo.value.query.idMult = ids
  }
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    isPagerByExport: dialogInfo.value.flag === 'page' ? true : false,
  }
  exportIncomeCostDetail(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

function pullData() {
  let params = {
    ...filterInfo.value.query,
  }
  pullDataIncomeCostDetail(params).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

function syncData() {
  let params = {
    ...filterInfo.value.query,
  }
  syncDataIncomeCostDetail(params).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

function downloadTemplate() {
  exportTemplateExcel('asset_income_cost_detail_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function allSummary(row = undefined) {
  const ids = _getIds(row)
  summaryAllIncomeCostDetail(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function summary(row = undefined) {
  const ids = _getIds(row)
  summaryIncomeCostDetail(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function cancelSummary(row = undefined) {
  const ids = _getIds(row)
  cancelSummaryIncomeCostDetail(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function returnModify() {
  getList()
}
// 获取列表
function getList() {
  tableInfo.value.api = getIncomeCostDetailPage
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  if (businessDate.value && businessDate.value.length) {
    filterInfo.value.query.businessDateGreater = businessDate.value[0]
    filterInfo.value.query.businessDateLess = businessDate.value[1]
  } else {
    filterInfo.value.query.businessDateGreater = ''
    filterInfo.value.query.businessDateLess = ''
    businessDate.value = []
  }
  if (filterInfo.value.query.assetId) {
    filterInfo.value.query.assetId = ''
  }
  getList()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      if (tableInfo.value.data && tableInfo.value.data.length) {
        tableInfo.value.data = tableInfo.value.data.map((item) => {
          if (item.assetCostDetailVOList && item.assetCostDetailVOList.length) {
            item.assetCostDetailVOList.forEach((el) => {
              item[el.costProject] = el.amount
            })
          }
          return item
        })
      }
      break
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//创建
function create() {
  modifyInfo.value.title = '新增设备收支明细'
  modifyInfo.value.visible = true
  modifyInfo.value.orderId = null
}
//更新
function update(row) {
  modifyInfo.value.title = '修改设备收支明细'
  modifyInfo.value.orderId = row.id
  modifyInfo.value.visible = true
}
//跳转资产卡片详情
function showDetail(row) {
  if (row.assetId && row.assetId !== -2) {
    assetDetailInfo.value.id = row.assetId
    assetDetailInfo.value.visible = true
  }
}

//删除
function del(row = undefined) {
  const ids = _getIds(row)
  if (row && row.id) {
    deleteIncomeCostDetail(ids).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        deleteIncomeCostDetail(ids).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  }
}

function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.value.selections.length > 0) {
      ids = tableInfo.value.selections.map((row) => row.id)
    }
  }
  return ids
}
function getCostFieldList() {
  //获取支出项目字段
  tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
    tableInfo.value.fieldList2
  )
  let asset_cost_project =
    proxy.$store.state.permission.dict['asset_cost_project']
  if (asset_cost_project && asset_cost_project.length) {
    let fieldList = asset_cost_project.map((item) => {
      let obj = {
        label: item.name + '(元)',
        value: item.code,
        formatter: proxy.$fn.TripartiteMethodAsset,
      }
      return obj
    })
    tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
      fieldList,
      tableInfo.value.fieldList2
    )
    getList()
  } else {
    setTimeout(() => {
      getCostFieldList()
    }, 100)
  }
}
onMounted(() => {
  getCostFieldList()
})
</script>

<style scoped></style>
